package org.redis.conf;

import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.redis.attribute.RedisConfigProperties;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.client.codec.StringCodec;
import org.redisson.config.ClusterServersConfig;
import org.redisson.config.Config;
import org.redisson.config.SingleServerConfig;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * RedissonConfig
 *
 * @author grl
 * @date 2023/3/16
 */
@Configuration
@RequiredArgsConstructor
public class RedissonConfig {

    private final RedisConfigProperties properties;


    @Bean(destroyMethod = "shutdown")
    public RedissonClient getRedisson() {
        Config config = new Config();
        config.setCodec(StringCodec.INSTANCE);
        List<String> nodes = properties.getCluster().getNodes();
        if (!CollectionUtils.isEmpty(nodes)) {
            // 集群
            List<String> nodeList = nodes.stream().map(node -> {
                if (!node.startsWith("redis://")) {
                    node = "redis://" + node;
                }
                return node;
            }).collect(Collectors.toList());
            ClusterServersConfig clusterServersConfig = config.useClusterServers().addNodeAddress(nodeList.toArray(new String[nodeList.size()]));
            String password = properties.getPassword();
            if (StringUtils.isNotBlank(password)) {
                //设置密码
                clusterServersConfig.setPassword(password);
            }
            //redis连接心跳检测，防止一段时间过后，与redis的连接断开
            clusterServersConfig.setPingConnectionInterval(32000);
        } else {
            // 单机
            //单机模式  依次设置redis地址和密码
            SingleServerConfig singleServerConfig = config.useSingleServer();
            singleServerConfig.setAddress("redis://" + properties.getHost() + ":" + properties.getPort()).setDatabase(properties.getDatabase()).setTimeout(properties.getTimeout()).setConnectTimeout(properties.getConnectTimeout()).setPingConnectionInterval(32000);
            if (StringUtils.isNotBlank(properties.getPassword())) {
                singleServerConfig.setPassword(properties.getPassword());
            }
        }
        return Redisson.create(config);
    }
}
